﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright company="DHGMS Solutions" file="Base.cs">
//   2004-2012 DHGMS Solutions. Some Rights Reserved. Licensed under GNU General Public License version 2 (GPLv2)
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System;
using System.Diagnostics.Contracts;
using System.Threading.Tasks;
using Dhgms.TplHelper.Model.Info;

namespace Dhgms.TplHelper.Tasks
{
    /// <summary>
    /// JobBase class for a task
    /// </summary>
    /// <typeparam name="TTaskResultClass">
    /// The type of result being returned by the task
    /// </typeparam>
    public abstract class TaskBase<TTaskResultClass>
        where TTaskResultClass : TaskResultBase, new()
    {
        /// <summary>
        /// Name of the current task
        /// </summary>
        private readonly string _name;

        /// <summary>
        /// Initializes a new instance of the <see cref="JobBase{TTaskResultClass}"/> class. 
        /// </summary>
        /// <param name="name">
        /// The task Name.
        /// </param>
        protected TaskBase(string name)
        {
            Contract.Requires<ArgumentNullException>(!string.IsNullOrWhiteSpace(name), "name");

            _name = name;
        }

        /// <summary>
        /// Gets the reference for the task. Used to give extended information on what the task is actually processing. i.e. a username or product id
        /// </summary>
        protected abstract string Reference { get; }

        /// <summary>Entry point for doing the donkey work.</summary>
        /// <returns>The Execution Result.</returns>
        public async Task<TTaskResultClass> Execute()
        {
            var started = DateTime.Now;
            Console.WriteLine("Starting Task: " + _name);
            var result = new TTaskResultClass();
            await OnProcess(result);
            Console.WriteLine("Finished Task: " + _name);

            result.Name = _name;
            result.Started = started;
            result.Finished = DateTime.Now;
            return result;
        }

        /// <summary>
        /// The OnProcess event for doing the donkey work
        /// </summary>
        protected abstract Task OnProcess(TTaskResultClass resultInformation);
    }
}